package com.fjec.im.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjec.common.enums.EnumSysCode;
import com.fjec.common.protocol.JsonResult;
import com.fjec.common.shiro.AccountInfo;
import com.fjec.common.util.DateUtil;
import com.fjec.im.entity.BizSystemMessage;
import com.fjec.im.entity.BizUserConversation;
import com.fjec.im.entity.BizUserMessage;
import com.fjec.im.mapper.BizSystemMessageMapper;
import com.fjec.im.mapper.BizUserConversationMapper;
import com.fjec.im.mapper.BizUserMessageMapper;
import com.fjec.im.service.IBizUserMessageService;
import com.fjec.im.view.UserMessageVO;
import com.vdurmont.emoji.EmojiParser;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 013.用户留言表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2020-09-23
 */
@Service
public class BizUserMessageServiceImpl extends ServiceImpl<BizUserMessageMapper, BizUserMessage> implements IBizUserMessageService {

    @Resource
    private BizUserMessageMapper mapper;

    @Resource
    private BizUserConversationMapper bizUserConversationMapper;

    @Resource
    private BizSystemMessageMapper systemMessageMapper;

    @Override
    public JsonResult getList(Page page, Long convId) {
        QueryWrapper<BizUserMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ConvId", convId)
                .orderByDesc("CreateTime");
        Page<BizUserMessage> resultPage = mapper.selectPage(page, queryWrapper);
        List<UserMessageVO> resultList = new ArrayList<>();
        Long userId = AccountInfo.getUserId();
        for (BizUserMessage entity : resultPage.getRecords()) {
            Long fromId = entity.getFromId();
            UserMessageVO view = new UserMessageVO();
            view.setId(entity.getId());
            view.setConvId(entity.getConvId());
            view.setUserId(fromId);
            view.setContent(entity.getContent());
            view.setCreateTime(entity.getCreateTime());
            Long createTime = DateUtil.ldt2Milli(entity.getCreateTime());
            view.setStrCreateTime(String.valueOf(createTime / 1000));
            if (userId.longValue() == fromId.longValue()) {
                view.setIsSelf(1);
            } else {
                view.setIsSelf(0);
            }
            resultList.add(view);
        }
        this.setAllReaded(convId);
        return JsonResult.success()
                .total(resultPage.getTotal())
                .data(resultList)
                .build();
    }

    @Override
    public JsonResult save(Long convId, Long toId, String content) {
        BizUserMessage entity = new BizUserMessage();
        entity.setConvId(convId);
        entity.setFromId(AccountInfo.getUserId());
        entity.setToId(toId);
        entity.setContent(content);
        entity.setCreateTime(DateUtil.nowLdt());
        entity.setReaded(0);
        mapper.insert(entity);
        return JsonResult.success()
                .code(EnumSysCode.MSG_6002.getCode())
                .message(EnumSysCode.MSG_6002.getMsg())
                .build();
    }

    @Override
    public int setAllReaded(Long convId) {
        UpdateWrapper<BizUserMessage> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("ConvId", convId)
                .eq("Readed", 0)
                .eq("ToId", AccountInfo.getUserId());
        BizUserMessage entity = new BizUserMessage();
        entity.setReaded(1);
        entity.setUpdateTime(DateUtil.nowLdt());
        int count = mapper.update(entity, updateWrapper);
        return count;
    }

    @Override
    public Map<String, Object> getUnReadNum() {
        Long userId = AccountInfo.getUserId();
        return this.getUnReadNum(userId);
    }

    @Override
    public Map<String, Object> getUnReadNum(Long userId) {
        Map<String, Object> resultMap = new HashMap<>();
        // 会话数量
        QueryWrapper<BizUserConversation> convQuery = new QueryWrapper<>();
        convQuery.eq("UserId1", userId).or().eq("UserId2", userId);
        int convMsgNum = bizUserConversationMapper.selectCount(convQuery);
        resultMap.put("convNum", convMsgNum);
        // 有会话才去查未读消息数量
        if (convMsgNum > 0) {
            // 未读消息数
            QueryWrapper<BizUserMessage> msgQuery = new QueryWrapper<>();
            msgQuery.eq("Readed", 0)
                    .eq("ToId", userId);
            int unReadMsgNum = mapper.selectCount(msgQuery);
            resultMap.put("msgNum", unReadMsgNum);
        } else {
            resultMap.put("msgNum", 0);
        }
        // 查询系统消息数量
        QueryWrapper<BizSystemMessage> querySysMsg = new QueryWrapper<>();
        querySysMsg.eq("UserId", userId)
                    .eq("Readed", 0);
        Integer sysMsgNum = systemMessageMapper.selectCount(querySysMsg);
        if (sysMsgNum == null || sysMsgNum.intValue() == 0) {
            resultMap.put("sysMsgNum", null);
        } else {
            resultMap.put("sysMsgNum", sysMsgNum);
        }
        return resultMap;
    }
}
